<template>
	<view class="tui-container" catch:touchmove="touchmove">
		<movable-area class="movarea" ref="areaBox" id="areaBox">
		<view class="tui-upload-box">
			<!-- <view class="tui-image-item" v-for="(item,index) in imageList" @bindlongpress='_longtap' @bindtouchstart='touchs' @bindtouchend='touchend' @bindtouchmove='touchm' :key="index"> -->
			<view v-if="item.url" class="tui-image-item" v-for="(item,index) in scopeImgList" :key="index">
				<image
					:id="'img' + index"
					:ref="'img' + index"
					:src="item.url"
					mode="aspectFill"
					@touchstart="tstr(index, $event)"
					@touchmove="tsmo"
					@touchend="toend"
					class="tui-item-img"
					:class="(hoverImgIdx==='img'+index)?'select':''"
				></image>
				<!-- <image v-if="item" :src="item" class="tui-item-img" @tap.stop="previewImage(index)" mode="aspectFill"></image> -->
				<view v-if="!forbidDel" class="tui-img-del" @tap.stop="delImage(index)"></view>
				<view v-if="statusArr[index]!=1" class="tui-upload-mask">
					<view class="tui-upload-loading" v-if="statusArr[index]==2"></view>
					<text class="tui-tips">{{statusArr[index]==2?'上传中...':'上传失败'}}</text>
					<view class="tui-mask-btn" v-if="statusArr[index]==3" @tap.stop="reUpLoad(index)" hover-class="tui-hover"
					 :hover-stay-time="150">重新上传</view>
				</view>
			</view>
			<view v-if="isShowAdd" class="tui-upload-add" @tap="chooseImage">
				<view class="tui-upload-icon tui-icon-plus"></view>
			</view>
		</view>
		<movable-view v-if="moveSrc" :animation="false" class="moveV" :x="x" :y="y" direction="all" @change="onChange"  :style="{ width: imgSize + 'px', height: imgSize + 'px' }">
			<image :src="moveSrc" mode="aspectFill" ></image>
		</movable-view>
		</movable-area>
	</view>
</template>

<script>
	const dataTime = require('../../utils/util.js');
	const app = require('../../App.vue');
	const VUE = 'vue';
	
	export default {
		name: 'tuiUpload',
		props: {
			imgList: {
				type: Array,
				default: function() {
					return [];
				}
			},
			imgSize: {
				type: Number,
				default: function() {
					return 105;
				}
			},
			//初始化图片路径
			value: {
				type: Array,
				default () {
					return []
				}
			},
			itemList: {
				type: Array,
				default: function() {
					return []
				}
			},
			//禁用删除
			forbidDel: {
				type: Boolean,
				default: false
			},
			//禁用添加
			forbidAdd: {
				type: Boolean,
				default: false
			},
			//服务器地址
			serverUrl: {
				type: String,
				default: ""
			},
			//限制数
			limit: {
				type: Number,
				default: 9
			},
			//项目名，默认为 file
			fileKeyName: {
				type: String,
				default: "file"
			}
		},
		data() {
			return {
				//图片地址
				imageList: [],
				//上传状态：1-上传成功 2-上传中 3-上传失败
				statusArr: [],
				
				scopeImgList:[],
				areaBoxInfo: {},
				x: 0,
				y: 0,
				idx: 0,
				moveSrc: '',
				areaBoxTop: 0,
				hoverImgIdx:'',
				inBoxXY:{}
			}
		},
		created() {
			this.imageList = [...this.value];
			for (let item of this.imageList) {
				this.statusArr.push("1")
			}
			console.log('获取图片',this.imageList);
			// for(let i = 0; i<this.itemList.length;i++){
			// 	this.statusArr.push(1)
			// }
			// this.imageList = this.itemList
			this.itemList = [];
		},
		mounted(){
			var goods_list = [];
			this.scopeImgList = [];
			var count = 0;
			for (let s = 0; s < this.itemList.length; s++) {
				if(this.itemList[s]){
					goods_list[count] = this.itemList[s];
					count = count + 1;
				}
			}
			this.itemList = goods_list;
			
			for(let i = 0; i<this.itemList.length;i++){
				this.statusArr.push(1);
				this.scopeImgList.push({'url':this.itemList[i]});
			}
			this.imageList = this.itemList;
			console.log('获取图片',this.imageList);
			
			let _this = this;
			this.getDomInfo('areaBox', info => {
				_this.areaBoxInfo = info;
				// 设置区域内所有图片的左上角坐标
				_this.scopeImgList.forEach((item, idx) => {
					_this.getDomInfo('img' + idx, res => {
						item.x = res.left-info.left;
					});
					_this.getDomInfo('img' + idx, res => {
						item.y = res.top-info.top;
					});
				});
			});
			
		},
		computed: {
			isShowAdd() {
				let isShow = true;
				if (this.forbidAdd || (this.limit && this.imageList.length >= this.limit)) {
					isShow = false;
				}
				
				return isShow
			}
		},
		methods: {
			Toobtainposition() {
				let _this = this;
				this.getDomInfo('areaBox', info => {
					_this.areaBoxInfo = info;
					// 设置区域内所有图片的左上角坐标
					_this.scopeImgList.forEach((item, idx) => {
						_this.getDomInfo('img' + idx, res => {
							item.x = res.left-info.left;
						});
						_this.getDomInfo('img' + idx, res => {
							item.y = res.top-info.top;
						});
					});
				});
				console.log(_this.scopeImgList);
			},
			moveHandle() {
				return;
			},
			onChange(e) {
				// console.log(e.detail)
			},
			tstr(e, s) {
				this.Toobtainposition();
				const _this = this;
				//获取拖拽区域的上边距和下边距
				let areaBoxTop = this.areaBoxInfo.top;
				let areaBoxLeft = this.areaBoxInfo.left;
				// console.log(this.areaBoxInfo)
				
				// 设置可移动方块的初始位置为当前所选中图片的位置坐标
				this.x = this.scopeImgList[e].x;
				this.y = this.scopeImgList[e].y;
				//显示可移动方块
				this.moveSrc = this.scopeImgList[e].url;
				//保存当前所选择的图片索引
				this.idx = e;
				var x = s.changedTouches[0].clientX-areaBoxLeft;
				var y = s.changedTouches[0].clientY-areaBoxTop;
				// 保存鼠标在图片内的坐标
				this.inBoxXY={
					x:x-this.scopeImgList[e].x,
					y:y-this.scopeImgList[e].y,
				}
			},
			tsmo(e) {
				const _this = this;
				let areaBoxTop = this.areaBoxInfo.top;
				let areaBoxLeft = this.areaBoxInfo.left;
				let  imgSize= this.imgSize;
				//重置为以拖拽盒子左上角为坐标原点
				var x = e.changedTouches[0].clientX-areaBoxLeft;
				var y = e.changedTouches[0].clientY-areaBoxTop;
				this.x = x-this.inBoxXY.x;
				this.y = y-this.inBoxXY.y;
				
				this.scopeImgList.forEach((item, idx) => {
					if (x>item.x&&x<item.x+imgSize&&y>item.y&&y<item.y+imgSize) {
						_this.hoverImgIdx='img'+idx
					}
				});
			},
			toend(e) {
				const _this = this;
				let areaBoxTop = this.areaBoxInfo.top;
				let areaBoxLeft = this.areaBoxInfo.left;
				let  imgSize= this.imgSize;
				//重置为以拖拽盒子左上角为坐标原点
				var x = e.changedTouches[0].clientX-areaBoxLeft;
				var y = e.changedTouches[0].clientY-areaBoxTop;
				for(let idx in this.scopeImgList){
					let item=this.scopeImgList[idx];
					if (x>item.x&&x<item.x+imgSize&&y>item.y&&y<item.y+imgSize) {
						_this.scopeImgList[_this.idx].url = _this.scopeImgList[idx].url;
						_this.scopeImgList[idx].url = _this.moveSrc;
						break;
					}
				}
				// 移动结束隐藏可移动方块
				this.moveSrc = '';
				this.hoverImgIdx=''
				this.statusArr = [];
				var imageList_xin = [];
				
				console.log(this.scopeImgList);
				for (let i = 0; i < this.scopeImgList.length; i++) {
					let url = this.scopeImgList[i].url;
					imageList_xin.push(url);
				}
				this.imageList = imageList_xin;
				console.log('返回内容',this.imageList);
				for (let item of this.imageList) {
					this.statusArr.push("1")
				}
				this.$emit('complete', {
					imgArr: this.imageList
				})
				
				this.$emit('moveEndList', this.scopeImgList);
			},
			addImgBtn(){
				this.$emit('addImg');
			},
			closeImg(e) {
				this.$emit('delImgIdx', e);
			},
			getDomInfo(id, callBack) {
				const query = uni.createSelectorQuery().in(this);
				// console.log(query)
				query.select('#' + id)
					.boundingClientRect()
					.exec(function(res) {
						callBack(res[0]);
					});
			},
			
			// 重新调用图片方法
			photograph: function(itemList){
				this.scopeImgList = [];
				for(let i = 0; i<itemList.length;i++){
					this.statusArr.push(1);
					this.scopeImgList.push({'url':itemList[i]});
				}
				this.Toobtainposition();
				this.imageList = itemList;
				console.log('重新加载图片',this.imageList);
			},
			// 重新上传
			reUpLoad(index) {
				this.$set(this.statusArr, index, "2")
				this.change()
				this.uploadImage(index, this.imageList[index]).then(() => {
					this.change()
				}).catch(() => {
					this.change()
				})
			},
			change() {
				let status = ~this.statusArr.indexOf("2") ? 2 : 1
				if (status != 2 && ~this.statusArr.indexOf("3")) {
					// 上传失败
					status = 3
				}
				this.$emit('complete', {
					status: status,
					imgArr: this.imageList
				})
			},
			chooseImage: function() {
				let _this = this;
				uni.chooseImage({
					count: _this.limit - _this.imageList.length,
					success: function(e) {
						let imageArr = [];
						for (let i = 0; i < e.tempFilePaths.length; i++) {
							let len = _this.imageList.length;
							if (len >= _this.limit) {
								uni.showToast({
									title: `最多可上传${_this.limit}张图片`,
									icon: "none"
								});
								break;
							}
							let path = e.tempFilePaths[i]
							imageArr.push(path)
							_this.imageList.push(path);
							_this.statusArr.push("2");
							_this.scopeImgList.push({'url':path});
							_this.Toobtainposition();
						}
						_this.change()

						let start = _this.imageList.length - imageArr.length
						for (let j = 0; j < imageArr.length; j++) {
							let index = start + j
							//服务器地址
							if (_this.serverUrl) {
								_this.uploadImage(index, imageArr[j]).then(() => {
									_this.change()
								}).catch(() => {
									_this.change()
								})
							} else {
								//无服务器地址则直接返回成功
								_this.$set(_this.statusArr, index, "1")
								_this.change()
							}
						}
					}
				})
			},
			uploadImage: function(index, url) {
				let _this = this;
				_this.imageList[index] = null;
				let userInfo = uni.getStorageSync("userInfo");
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.serverUrl,
						name: this.fileKeyName,
						header: {
							//设置请求头
							'Content-Type':'application/json;charset=utf8',
							//设置请求头
						},
						formData: {
							token: userInfo.token
						},
						filePath: url,
						success: function(res) {
							if (res.statusCode == 200) {
								//返回结果 此处需要按接口实际返回进行修改
								let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
								//判断code，以实际接口规范判断
								if (d.code == '0000') {
									console.log('这个是状态 ',_this.statusArr,index)
									// 上传成功 d.url 为上传后图片地址，以实际接口返回为准
									d.filename && (_this.imageList[index] = _this.tui.uploadDomain() + d.filename)
									// _this.scopeImgList.splice(index);
									// _this.scopeImgList.push({'url':_this.tui.uploadDomain() + d.filename});
									_this.scopeImgList[index].url = _this.tui.uploadDomain() + d.filename;
									// _this.Toobtainposition();
									_this.$set(_this.statusArr, index, _this.tui.uploadDomain() + d.filename ? "1" : "3")
								} else {
									// 上传失败
									// _this.scopeImgList.splice(index);
									// _this.Toobtainposition();
									_this.$set(_this.statusArr, index, "3")
									// wx.showToast({
									// 	title: '上传失败',
									// 	image: '../../static/toast/fail-circle.png',
									// 	duration: 1000
									// })
									return false
								}
								resolve(index)
							} else {
								_this.$set(_this.statusArr, index, "3")
								reject(index)
							}
						},
						fail: function(res) {
							_this.$set(_this.statusArr, index, "3")
							reject(index)
						}
					})
				})

			},
			delImage: function(index) {
				this.imageList.splice(index, 1)
				this.statusArr.splice(index, 1)
				this.scopeImgList.splice(index, 1)
				this.$emit("remove", {
					index: index
				})
				this.Toobtainposition();
				this.change()
			},
			previewImage: function(index) {
				if (!this.imageList.length) return;
				uni.previewImage({
					current: this.imageList[index],
					loop: true,
					urls: this.imageList
				})
			},
		}
	}
</script>

<style lang="less">
	@font-face {
		font-family: 'tuiUpload';
		src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATcAA0AAAAAByQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAAEwAAAABoAAAAciR52BUdERUYAAASgAAAAHgAAAB4AKQALT1MvMgAAAaAAAABCAAAAVjxvR/tjbWFwAAAB+AAAAEUAAAFK5ibpuGdhc3AAAASYAAAACAAAAAj//wADZ2x5ZgAAAkwAAADXAAABAAmNjcZoZWFkAAABMAAAAC8AAAA2FpiS+WhoZWEAAAFgAAAAHQAAACQH3QOFaG10eAAAAeQAAAARAAAAEgwAACBsb2NhAAACQAAAAAwAAAAMAEoAgG1heHAAAAGAAAAAHwAAACABEgA2bmFtZQAAAyQAAAFJAAACiCnmEVVwb3N0AAAEcAAAACgAAAA6OMUs4HjaY2BkYGAAYo3boY/i+W2+MnCzMIDAzb3qdQj6fwPzf+YGIJeDgQkkCgA/KAtvAHjaY2BkYGBu+N/AEMPCAALM/xkYGVABCwBZ4wNrAAAAeNpjYGRgYGBl0GJgZgABJiDmAkIGhv9gPgMADTABSQB42mNgZGFgnMDAysDA1Ml0hoGBoR9CM75mMGLkAIoysDIzYAUBaa4pDA7PGJ9xMjf8b2CIYW5gaAAKM4LkANt9C+UAAHjaY2GAABYIVmBgAAAA+gAtAAAAeNpjYGBgZoBgGQZGBhBwAfIYwXwWBg0gzQakGRmYnjE+4/z/n4EBQksxSf6GqgcCRjYGOIeRCUgwMaACRoZhDwCiLwmoAAAAAAAAAAAAAAAASgCAeNpdjkFKw0AARf/vkIR0BkPayWRKQZtYY90ohJju2kOIbtz0KD1HVm50UfEmWXoAr9ADOHFARHHzeY//Fx8Ci+FJfIgdJFa4AhgiMshbrCuIsLxhFJZVs+Vl1bT1GddtbXTC3OhohN4dg4BJ3zMJAnccyfm468ZzHXddrH9ZKbHzdf9n/vkY/xv9sPQXgGEvBrHHwst5kTbXLE+YpYVPkxepPmW94W16UbdNJd6f3SAzo5W7m1jaKd+8ZZIvk5nlKw9SK6Wle7BLS3f/bTzQLmfAF2T1NsQAeNp9kD1OAzEQhZ/zByQSQiCoXVEA2vyUKRMp9Ailo0g23pBo1155nUg5AS0VB6DlGByAGyDRcgpelkmTImvt6PObmeexAZzjGwr/3yXuhBWO8ShcwREy4Sr1F+Ea+V24jhY+hRvUf4SbuFUD4RYu1BsdVO2Eu5vSbcsKZxgIV3CKJ+Eq9ZVwjfwqXMcVPoQb1L+EmxjjV7iFa2WpDOFhMEFgnEFjig3jAjEcLJIyBtahOfRmEsxMTzd6ETubOBso71dilwMeaDnngCntPbdmvkon/mDLgdSYbh4FS7YpjS4idCgbXyyc1d2oc7D9nu22tNi/a4E1x+xRDWzU/D3bM9JIbAyvkJI18jK3pBJTj2hrrPG7ZynW814IiU68y/SIx5o0dTr3bmniwOLn8owcfbS5kj33qBw+Y1kIeb/dTsQgil2GP5PYcRkAAAB42mNgYoAALjDJyIAOWMGiTIxMjMxsKak5qSWpbFmZiRmJ+QAmgAUIAAAAAf//AAIAAQAAAAwAAAAWAAAAAgABAAMABAABAAQAAAACAAAAAHjaY2BgYGQAgqtL1DlA9M296nUwGgA+8QYgAAA=) format('woff');
		font-weight: normal;
		font-style: normal;
	}

	.tui-upload-icon {
		font-family: "tuiUpload" !important;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		padding: 10rpx;
	}

	.tui-icon-delete:before {
		content: "\e601";
	}

	.tui-icon-plus:before {
		content: "\e609";
	}

	.tui-upload-box {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}

	.tui-upload-add {
		width: 220rpx;
		height: 220rpx;
		font-size: 68rpx;
		font-weight: 100;
		color: #888;
		background-color: #F7F7F7;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}

	.tui-image-item {
		width: 220rpx;
		height: 220rpx;
		position: relative;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.tui-image-item:nth-of-type(3n) {
		margin-right: 0;
	}

	.tui-item-img {
		width: 220rpx;
		height: 220rpx;
		display: block;
	}

	.tui-img-del {
		width: 36rpx;
		height: 36rpx;
		position: absolute;
		right: -12rpx;
		top: -12rpx;
		background: #EB0909;
		border-radius: 50%;
		color: white;
		font-size: 34rpx;
		z-index: 999;
	}

	.tui-img-del::before {
		content: '';
		width: 16rpx;
		height: 1px;
		position: absolute;
		left: 10rpx;
		top: 18rpx;
		background: #fff;
	}

	.tui-upload-mask {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		padding: 40rpx 0;
		box-sizing: border-box;
		background: rgba(0, 0, 0, 0.6);
	}

	.tui-upload-loading {
		width: 28rpx;
		height: 28rpx;
		border-radius: 50%;
		border: 2px solid;
		border-color: #B2B2B2 #B2B2B2 #B2B2B2 #fff;
		animation: tui-rotate 0.7s linear infinite;
	}

	@keyframes tui-rotate {
		0% {
			transform: rotate(0);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.tui-tips {
		font-size: 26rpx;
		color: #fff;
	}

	.tui-mask-btn {
		padding: 6rpx 16rpx;
		border-radius: 40rpx;
		text-align: center;
		font-size: 24rpx;
		color: #fff;
		border: 1rpx solid #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tui-hover {
		opacity: 0.5;
	}
	
	
	.movarea {
		width: 100%;
		height: 100%;
		// background-color: #0901ff;
		display: flex;
		flex-direction: row;
	}
	
	.imgBox {
		width: 100%;
		height: 160px;
		// background-color: #09BB07;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		.imgItem {
			
			position: relative;
			image {
				width: 105px;
				height: 105px;
				transition: all 0.5s;
				vertical-align: top;
			}
			.closeBtn {
				background-color: red;
				color: #FFFFFF;
				border-radius: 50%;
				text-align: center;
				position: absolute;
				top: 0;
				right: 0;
				width: 20px;
				height: 20px;
				line-height: 20px;
				z-index: 3;
				transform: translate(50%, -50%);
			}
		}
	
		// .addImgBtn {
		// 	background-color: #d0d0d0;
		// }
	}
	
	.moveV {
		opacity: 0.8;
		z-index: 999;
		image {
			width: 105px;
			height: 105px;
		}
	}
	.select{
		transform: scale(1.3);
	}
</style>
